package com.wx.kit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpKit {

	public static String getResponse(HttpResponse response) throws IOException {
		StringBuffer jsonStr = new StringBuffer();
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			InputStream in = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				jsonStr.append(line);
			}
			in.close();
			reader.close();
		}
		return jsonStr.toString();
	}

	public static HttpResponse httpRequest(String url) throws ClientProtocolException, IOException {
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost request = new HttpPost(url);
		HttpResponse response = client.execute(request);
		return response;
	}

	public static HttpResponse httpRequestPostJson(String url, String json) throws ClientProtocolException, IOException {
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost request = new HttpPost(url);
		StringEntity postingString = new StringEntity(json, "UTF-8");// json传递
		request.setEntity(postingString);
		request.setHeader("Content-type", "application/json; charset=UTF-8");
		HttpResponse response = client.execute(request);
		return response;
	}
}
